/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.em.service.impl;

import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.cspimp.em.domain.Command;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.em.repository.CommandRepository;
import me.zhengjie.modules.cspimp.em.service.CommandService;
import me.zhengjie.modules.cspimp.em.service.dto.CommandDto;
import me.zhengjie.modules.cspimp.em.service.dto.CommandQueryCriteria;
import me.zhengjie.modules.cspimp.em.service.mapstruct.CommandMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-24
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class CommandServiceImpl implements CommandService {

    private final CommandRepository commandRepository;
    private final CommandMapper commandMapper;
    private final UserRepository userRepository;


    @Override
    public Map<String, Object> queryAll(CommandQueryCriteria criteria, Pageable pageable) {

        List<Command> commandList = commandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<CommandDto> commands = new ArrayList<>();
        for (Command command : commandList) {
            CommandDto commandDto = new CommandDto();
            BeanUtils.copyProperties(command, commandDto);
            User user = userRepository.findById(commandDto.getUserId()).get();
            if (null != user) {
                commandDto.setUsername(user.getUsername());
                commandDto.setPhone(user.getPhone());
            }

            commands.add(commandDto);
        }
        return PageUtil.toPage(PageUtil.listPage(commands, pageable));
    }

    @Override
    public List<CommandDto> queryAll(CommandQueryCriteria criteria) {
        return commandMapper.toDto(commandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public CommandDto findById(Long id) {
        Command command = commandRepository.findById(id).orElseGet(Command::new);
        ValidationUtil.isNull(command.getId(), "Command", "id", id);
        CommandDto commandDto = new CommandDto();
        BeanUtils.copyProperties(command, commandDto);
        System.err.println("commandUserId:" + commandDto.getUserId());
        User user = userRepository.findById(commandDto.getUserId()).get();
        if (null != user) {
            commandDto.setUsername(user.getUsername());
            commandDto.setPhone(user.getPhone());
        }
        return commandDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommandDto create(Command resources) {
        if (commandRepository.findByName(resources.getName()) != null) {
            throw new EntityExistException(Command.class, "name", resources.getName());
        }
        resources.setCid(0l);
        commandRepository.save(resources);
        return findById(resources.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Command resources) {
        Command command = commandRepository.findById(resources.getId()).get();
        ValidationUtil.isNull(command.getId(), "Command", "bid", resources.getId());
        Command c = commandRepository.findByName(resources.getName());

        if (c != null && !c.getId().equals(c.getId())) {
            throw new EntityExistException(Command.class, "name", resources.getName());
        }

        command.copy(resources);
        commandRepository.save(command);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            commandRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<CommandDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CommandDto command : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put(" cid", command.getCid());
            map.put("应急指挥名称", command.getName());
            map.put("职责", command.getDuty());
            map.put("指挥级别id", command.getCommandLevelCode());
            map.put("用户id", command.getUserId());
            map.put("创建时间", command.getCreateTime());
            map.put("更新时间", command.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}